
package ldk.util.radioview;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;

/**
 * Helper class for generate radioview
 * Created by ldkxingzhe@163.com on 2017/4/26.
 */
public final class RadioViewHelper {
    @SuppressLint("unused")
    private static final String TAG = "RadioViewHelper";
    public static  boolean DEBUG = true;
    private static final float NO_RADIO = -1;

    private float mWidthHeightRadio = NO_RADIO;

    public interface RadioViewListener{
        void setWidthHeightRadio(float radio);
    }

    private RadioViewListener mRadioViewListener;
    private View mAttachedView;

    public <T extends View & RadioViewListener> RadioViewHelper(T attachedView, @Nullable AttributeSet attrs){
        mAttachedView = attachedView;
        mRadioViewListener = attachedView;
        if (attrs != null){
            Context context = mAttachedView.getContext();
            TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.RadioView);
            mWidthHeightRadio = array.getFloat(R.styleable.RadioView_widthHeightRadio, NO_RADIO);
            array.recycle();
        }
    }

    public void setWidthHeightRadio(float radio){
        mWidthHeightRadio = radio;
        mAttachedView.requestLayout();
    }

    public void onMeasure() {
        if (mWidthHeightRadio == NO_RADIO) return;
        int widthState = mAttachedView.getMeasuredWidthAndState();
        int width = View.MeasureSpec.getSize(widthState);
        int mode = View.MeasureSpec.getMode(widthState);
        if (DEBUG){
            String modeStr = null;
            switch (mode){
                case View.MeasureSpec.AT_MOST:
                    modeStr = "AT_MOST";
                    break;
                case View.MeasureSpec.EXACTLY:
                    modeStr = "EXACTLY";
                    break;
                case View.MeasureSpec.UNSPECIFIED:
                    modeStr = "UNSPECIFIED";
                    break;
            }
            Log.d(TAG, "onMeasure, width is " + width + ", modeStr is " + modeStr);
        }
        if (width <= 0) return;
        int height = (int) (width / mWidthHeightRadio);
        ViewGroup.LayoutParams params = mAttachedView.getLayoutParams();
        if (height != params.height){
            params.height = height;
            mAttachedView.setLayoutParams(params);
            int widthResultSpec = View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY);
            int heightResultSpec = View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY);
            mAttachedView.measure(widthResultSpec, heightResultSpec);
        }
    }
}
